using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NorthwindWeb.Models;

namespace NorthwindWeb.Controllers
{   
    public class CustomerController : Controller
    {
		private readonly ICustomerRepository customerRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public CustomerController() : this(new CustomerRepository())
        {
        }

        public CustomerController(ICustomerRepository customerRepository)
        {
			this.customerRepository = customerRepository;
        }

        //
        // GET: /Customer/

        public ViewResult Index()
        {
            return View(customerRepository.AllIncluding(customer => customer.Orders, customer => customer.CustomerDemographics));
        }

        //
        // POST: /Customer/Create

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "CustomerID")]Customer customer)
        {
            if (ModelState.IsValid) {
                customerRepository.InsertOrUpdate(customer);
                customerRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Customer/Edit/5

        [HttpPost]
        public ActionResult Edit(Customer customer)
        {
            if (ModelState.IsValid) {
                customerRepository.InsertOrUpdate(customer);
                customerRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Customer/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            customerRepository.Delete(id);
            customerRepository.Save();

            return RedirectToAction("Index");
        }

        
        public JsonResult customerGridData(int rows, int page)
        {
        	var count = customerRepository.All.Count();
            var pageData = customerRepository.All.OrderBy(x => x.CustomerID).Skip((page - 1) * rows).Take(rows).Select(o => new {CustomerID = o.CustomerID, CompanyName = o.CompanyName, ContactName = o.ContactName, ContactTitle = o.ContactTitle, Address = o.Address, City = o.City, Region = o.Region, PostalCode = o.PostalCode, Country = o.Country, Phone = o.Phone, Fax = o.Fax});
            return Json(new { 
            page = page,
            records = count,
            rows = pageData,
            total = Math.Ceiling((decimal)count / rows)
            }, JsonRequestBehavior.AllowGet);
        }
        
        
    }
}

